from flask import request
from utils import redis_helper
import datetime


class RestrictTool:
    def get_redis_key(self, suffix) -> str:
        return "%s_%s" % (request.path, suffix)

    def add(self, notify_channel, timeout: int):
        if not notify_channel:
            raise Exception('no notify channel.')
        name = self.get_redis_key(notify_channel)
        redis_client = redis_helper.redis_util.get_redis_client()
        if not redis_client.exists(name):
            redis_client.incr(name)
            redis_client.expire(name, timeout)
        else:
            redis_client.incr(name)
        redis_client.close()

    def check(self, notify_channel, max_munber):
        name = self.get_redis_key(notify_channel)
        redis_client = redis_helper.redis_util.get_redis_client()
        data_exists = redis_client.exists(name)
        restric_number = redis_client.get(name)
        redis_client.close()
        if data_exists:
            if int(restric_number) >= max_munber:
                return True
            else:
                return False
        else:
            return False

    def delete(self, notify_channel):
        name = self.get_redis_key(notify_channel)
        redis_client = redis_helper.redis_util.get_redis_client()
        data_exists = redis_client.exists(name)
        if data_exists:
            redis_client.delete(name)



